/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
var currentLocationGraphic;
var currentLocation;

     function initGeolocation(map) {
       dojo.connect(window, 'resize', map,map.resize);
        if(navigator.geolocation){  
          navigator.geolocation.getCurrentPosition(zoomToLocation, locationError);
          watchId = navigator.geolocation.watchPosition(showLocation, locationError);
          currentLocation = new esri.layers.GraphicsLayer({id:"currentLocation"});
          map.addLayer(currentLocation);
        }
        else{
          alert("Browser doesn't support Geolocation. Visit http://caniuse.com to discover browser support for the Geolocation API.");
        }
      }

function locationError(error) {
 //error occurred so stop watchPosition
 if(navigator.geolocation){
   navigator.geolocation.clearWatch(watchId);
 }
 switch (error.code) {
 case error.PERMISSION_DENIED:
   console.log("GEOLOCATION ERROR: Location not provided");
   break;

 case error.POSITION_UNAVAILABLE:
   console.log("GEOLOCATION ERROR: Current location not available");
   break;

 case error.TIMEOUT:
   console.log("GEOLOCATION ERROR: Timeout");
   break;

 default:
   console.log("GEOLOCATION ERROR: unknown error");
   break;
 }
}

function addGraphic(pt){
 //var symbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, 12,
    //new esri.symbol.SimpleLineSymbol(
    //    esri.symbol.SimpleLineSymbol.STYLE_SOLID,
    //    new dojo.Color([210, 105, 30, 0.5]), 8), 
    //new dojo.Color([210, 105, 30, 0.9])
 //);
 var symbol = new esri.symbol.PictureMarkerSymbol("images/currentLocation.gif",34,34);
 currentLocationGraphic = new esri.Graphic(pt, symbol);
 currentLocation.add(currentLocationGraphic);
}

function zoomToLocation(location) {
 var pt = esri.geometry.geographicToWebMercator(new esri.geometry.Point(location.coords.longitude, location.coords.latitude));
 addGraphic(pt);    
}

function showLocation(location) {
    
 //zoom to the users location and add a graphic
 var pt = esri.geometry.geographicToWebMercator(new esri.geometry.Point(location.coords.longitude, location.coords.latitude));
 if (!currentLocationGraphic) {
   addGraphic(pt);
 }
 else { //move the graphic if it already exists
   currentLocationGraphic.setGeometry(pt);
 }
}

function zoomToCurrentLocation() {
    map.centerAt(currentLocationGraphic.geometry);
}

